<?php
/*
 * 该文件的作用说明：
 * 把数据从rabbitmq里面读取出来
 * 然后进行nosql的异构和聚合
 * 然后改变自己数据库的状态（这里暂略）
 * 这里同学们根据自己的需求去封装到项目中
 * */


/*加载所需类包*/
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;
require('../config/config.php');

//连接broker,创建一个rabbitmq连接
$connection = new AMQPStreamConnection($config['host'], $config['port'], $config['login'], $config['password'], $config['vhost']);

if(!$connection){
    echo "连接失败";
    exit();
}

/*声明一个通道*/
$channel = $connection->channel();

/*声明一个队列*/
$channel->queue_declare('qos_queue', false, true, false, false);

/*每次消费限流10000*/
$channel->basic_qos(null, 10000, null);

/*开启消费监听*/
$channel->basic_consume('qos_queue', '', false, false, false, false, function ($message)
{
    echo "\n--------\n";
    echo $message->body;
    echo "\n--------\n";

    /*从rabbitmq里面取出json数据*/
    $data_json = $message->body;

    /*把json数据编译后，放入$data变量，
    $data变量是个二维数组，代表多条mysql数据*/
    $data = json_decode($data_json, true);


    /*数据保存到redis异构库*/
    saveToRedis($data);

    /*数据保存到mongodb聚合库*/
    saveToMongodb($data);

    /*ack机制返回*/
    $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
});


while ($channel->is_consuming()) {
    // 测试时10秒后让进程死掉，正式环境这里第三个参数要填0而不是10
    $channel->wait(null, false, 10);
}

/*数据保存到redis异构库*/
function saveToRedis($messages){
    //连接本地的 Redis 服务,实际环境中大家封装redis类库和配置文件即可
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);

    foreach ($messages as $message){

        $key = 'sku_num_'.$message['sku_id'];
        $sku_num = 0;
        $sku_num_old = $redis->get($key);
        if(!empty($sku_num_old)){
            $sku_num = $sku_num_old - $message['num'];
        }else{
            //实际上是可从数据库获取，这里写个示例值
            $sku_num = 10000;
        }

        /*记录某个商品sku的库存在redis里*/
        $redis->set($key, $sku_num);
    }
    var_dump($redis->get($key));
}

/*数据保存到mongodb聚合库*/
function saveToMongodb($messages){

    return;

    foreach ($messages as $message){

        /*先从mongodb查询数据*/
        $select_sku_info_from_mongodb = select_sku_info_from_mongodb($message['sku_id']);

        //用以往库存数 - 销售数量 = 现在库存数。
        $sku_num = $select_sku_info_from_mongodb['sku_num']-$message['num'];


        $bulk = new \MongoDB\Driver\BulkWrite;

        /*修改聚合数据中的库存数*/

        //update table set sku_num = 777 where sku_id = 123

        $bulk->update(
            ['sku_id' => 123],
            ['$set' => ['sku_num' => $sku_num]],
            //如果upsert=true，如果query找到了符合条件的行，则修改这些行，如果没有找到，则追加一行符合query和obj的行。如果upsert为false，找不到时，不追加。
            //如果multi=true，则修改所有符合条件的行，否则只修改第一条符合条件的行。
            ['multi' => false, 'upsert' => false]
        );


        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
        $result = $manager->executeBulkWrite('goods.detail', $bulk, $writeConcern);
    }
}

/*从mongodb查询数据*/
function select_sku_info_from_mongodb($sku_id){

    $manager = new \MongoDB\Driver\Manager("mongodb://192.168.232.104:27017");

    $filter = ['sku_id' => ['$eq' => $sku_id]];
    $options = [];

    // 查询数据
    $query = new \MongoDB\Driver\Query($filter, $options);
    $cursor = $manager->executeQuery('goods.detail', $query);

    $data = [];
    foreach ($cursor as $document) {

        $data = json_decode( json_encode( $document),true);
    }

    /*不用研究这个方法，这个方法不过是插入聚合测试数据到mongodb而已*/
    if(!$data){
        /*不用研究这个方法，这个方法不过是插入测试数据而已*/
        doInsertExampleData($sku_id);

        $filter = ['sku_id' => ['$eq' => $sku_id]];
        $options = [];

        // 查询数据
        $query = new \MongoDB\Driver\Query($filter, $options);
        $cursor = $manager->executeQuery('goods.detail', $query);
        $data = [];
        foreach ($cursor as $document) {

            $data = json_decode( json_encode( $document),true);
        }
    }

    return $data;
}

/*
 * 不用研究这个方法，这个方法不过是插入聚合测试数据到mongodb而已
 * 插入聚合测试数据
*/
function doInsertExampleData($sku_id){
    $str = '{
        "sku_id":123,
        "sku_num":10000,
        "categoryPropertyViews": null, 
        "detailRedirectView": {
            "error": false, 
            "errorMsg": "", 
            "redirect": false, 
            "redirectUrl": null
        }, 
        "otherServiceView": {
            "moreUrl": null, 
            "otherList": [
                {
                    "logoUrl": "//img.alicdn.com/top/i1/TB1CcmzOUH1gK0jSZSySuttlpXa.jpg", 
                    "name": "详情定制_店铺装修设计_美工包月", 
                    "priceDesc": "3000元/人*月", 
                    "servScore": 0, 
                    "serviceType": 99, 
                    "url": "//fw.taobao.com/common/detail.html?code=FW_GOODS-1001099546&tracelog=other_serv"
                }, 
                {
                    "logoUrl": "//img.alicdn.com/top/i1/TB1GgKFdipE_u4jSZKbSuvCUVXa.jpg", 
                    "name": "严选无线电脑详情页定制设计", 
                    "priceDesc": "800元/个", 
                    "servScore": 0, 
                    "serviceType": 129, 
                    "url": "//fw.taobao.com/common/detail.html?code=FW_GOODS-1001099199&tracelog=other_serv"
                }, 
                {
                    "logoUrl": "//img.alicdn.com/top/i1/TB1lWlMdZVl614jSZKPwu1GjpXa.png", 
                    "name": "主图详情页设计店铺首页美工包月", 
                    "priceDesc": "400元/次", 
                    "servScore": 0, 
                    "serviceType": 24, 
                    "url": "//fw.taobao.com/common/detail.html?code=FW_GOODS-1001101907&tracelog=other_serv"
                }
            ], 
            "totalServ": 3
        }, 
        "scoreInfoView": {
            "attrViewGroup": [
                {
                    "desc": "30.48 %", 
                    "labelName": "复购率"
                }, 
                {
                    "desc": "0.02 %", 
                    "labelName": "退款率"
                }, 
                {
                    "desc": "100.00 %", 
                    "labelName": "打开率"
                }
            ], 
            "avgScore": "5.0", 
            "intervalGroup": [
                {
                    "endScore": 1, 
                    "percentage": "0.17", 
                    "startScore": 0
                }, 
                {
                    "endScore": 2, 
                    "percentage": "0.0", 
                    "startScore": 1
                }, 
                {
                    "endScore": 3, 
                    "percentage": "0.51", 
                    "startScore": 2
                }, 
                {
                    "endScore": 4, 
                    "percentage": "0.51", 
                    "startScore": 3
                }, 
                {
                    "endScore": 5, 
                    "percentage": "98.81", 
                    "startScore": 4
                }
            ], 
            "scoreNum": 591, 
            "scoreViewGroup": [
                {
                    "level": 1, 
                    "name": "描述相符", 
                    "percent": "0.55"
                }, 
                {
                    "level": 1, 
                    "name": "服务效果", 
                    "percent": "0.61"
                }, 
                {
                    "level": 1, 
                    "name": "服务效率", 
                    "percent": "0.59"
                }
            ]
        }, 
        "serviceInfoView": {
            "basePrice": "59.00", 
            "bigIcon": "//img.alicdn.com/top/i1/TB1bTtALNjaK1RjSZKzSutVwXXa.jpg", 
            "canShow": true, 
            "categoryPropertyViewList": null, 
            "comments": "主图短视频/神笔详情页模板制作/抠图换背景/白底图/透明图/拼图/美化/水印标签/美图秀秀图片处理/店铺装修", 
            "desc": "主图短视频/神笔详情页模板制作/抠图换背景/白底图/透明图/拼图/美化/水印标签/美图秀秀图片处理/店铺装修", 
            "errorMsg": null, 
            "freeUsers": "936", 
            "freeUsersDesc": "900+", 
            "icon": "//img.alicdn.com///img.alicdn.com/bao/uploaded/TB1o8mAOVXXXXajXVXXSutbFXXX", 
            "labelList": [
                {
                    "code": "pc", 
                    "gmtCreate": 1401869672000, 
                    "gmtModified": 1401869672000, 
                    "id": 227412, 
                    "name": "电脑版", 
                    "namespace": "platform", 
                    "operater": "万良", 
                    "status": 1
                }, 
                {
                    "code": "pcqnwork", 
                    "gmtCreate": 1401869672000, 
                    "gmtModified": 1401869672000, 
                    "id": 227414, 
                    "name": "千牛PC工作台插件", 
                    "namespace": "platform", 
                    "operater": "万良", 
                    "status": 1
                }
            ], 
            "labelName": [
                "电脑版", 
                "千牛PC工作台插件"
            ], 
            "moneyUsers": "9695", 
            "moneyUsersDesc": "9500+", 
            "name": "美图王_一站式图片装修", 
            "sale": {
                "isIcbuPC": false, 
                "isIcbuMobile": false, 
                "isShuang11": false
            }, 
            "spId": "2926218234", 
            "tpInfoView": {
                "hasTp": false, 
                "list": [ ]
            }, 
            "userCount": "10601", 
            "userCountDesc": "1.0万"
        }, 
        "spInfoView": {
            "address": "紫霞街176号互联网创新创业园1号楼", 
            "announcement": "五色云网络在线服务时间为: 9:00-22:00. 软件使用过程中有任何问题，请联系在线客服或致电18914087334，客服人员将会在最快时间内解答您的疑问！", 
            "categoryList": null, 
            "categoryNameList": [
                "设计服务", 
                "商品管理"
            ], 
            "city": "杭州市", 
            "createDate": "2016-07-05 20:09:16", 
            "customerLogoList": [
                {
                    "logo": "//img.alicdn.com/top/i1/TB16jxQgCf2gK0jSZFPSutsopXa.jpg", 
                    "name": "塞朵娅旗舰店"
                }
            ], 
            "description": "杭州五色云网络科技有限公司通过研发智能抠图技术，提高抠图效率，降低抠图门槛，同时专业设计师制作大量的背景素材、标签素材供淘宝卖家选择，一站式解决淘宝卖家做图痛点，降低做图成本，快速制作精美主图", 
            "email": null, 
            "iconGroup": [
                {
                    "code": "auth", 
                    "href": null, 
                    "src": "https://img.alicdn.com/tfs/TB1kuW3bB1D3KVjSZFyXXbuFpXa-30-16.png", 
                    "tag": "商家认证"
                }, 
                {
                    "code": "spLicense", 
                    "href": "//fuwu.taobao.com/ser/spLicense.htm?spId=2926218234", 
                    "src": "https://img.alicdn.com/tfs/TB14f51bwKG3KVjSZFLXXaMvXXa-16-16.png", 
                    "tag": "工商执照"
                }
            ], 
            "isAuth": null, 
            "isvApplySignOutDate": null, 
            "isvFinishSignOutDate": null, 
            "isvHomepageUrl": "//fuwu.taobao.com/serv/shop_index.htm?isv_id=2926218234", 
            "isvType": null, 
            "mobile": null, 
            "province": "浙江省", 
            "qualificationList": [
                {
                    "bailAmount": 20000, 
                    "name": "定制设计服务商", 
                    "spType": 18
                }
            ], 
            "seIsvType": null, 
            "serviceWangwang": "五色云科技008", 
            "shopLogoUrl": null, 
            "spId": "2926218234", 
            "spLicenseUrl": null, 
            "spLogoUrl": "//img.alicdn.com/top/i1/TB1m_4cKVXXXXcbXXXXwu0bFXXX.png", 
            "spName": "杭州五色云网络技术有限公司", 
            "spQualityRateViews": [
                {
                    "code": null, 
                    "name": "商品管理", 
                    "value": 5
                }
            ], 
            "spStatus": 1, 
            "tpInfoVIew": {
                "hasTp": false, 
                "list": [ ]
            }
        }, 
        "subView": {
            "sellerIndustry": [ ], 
            "sellerStar": [
                {
                    "label": "3心以下", 
                    "percent": ""
                }, 
                {
                    "label": "4心-5心", 
                    "percent": ""
                }, 
                {
                    "label": "1钻-3钻", 
                    "percent": ""
                }, 
                {
                    "label": "4钻-5钻", 
                    "percent": ""
                }, 
                {
                    "label": "1皇冠以上", 
                    "percent": ""
                }
            ], 
            "subRecord": 9695
        }, 
        "tabSwitchView": {
            "detailSwitch": true, 
            "scoreSwitch": true, 
            "tutorialSwitch": true
        }
    }';

    $bulk = new \MongoDB\Driver\BulkWrite;
    $arr = json_decode($str,true);
    $arr['_id'] =  new \MongoDB\BSON\ObjectID;

    /*插入数据到mongdodb*/
    $_id= $bulk->insert($arr);

    $manager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");
    $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
    $result = $manager->executeBulkWrite('goods.detail', $bulk, $writeConcern);

    return $arr;
}